import * as React from 'react';
import { } from 'react-router';
import { observer } from 'mobx-react'
import { RouteComponentProps } from 'react-router';
import { Form, Input, DatePicker, Button, Table, message } from 'antd';

import { ImageUploader } from '../../../../components/ImageUploader';
import { AdsModel } from '../../../../../model/assets/standard/AdsModel';
import { isUrl } from '../../../../../service/Validator';
import {CREATE_SUCCESS_REDIRECT_DELAY} from "../../../../../service/Config";

const FormItem = Form.Item;
const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
};
const tailFormItemLayout = {
    wrapperCol: {
        span: 14,
        offset: 6,
    },
};
const linkPlaceholder = "请输入广告跳转的链接,格式如:http://example.com";

type AdsEditorProps = RouteComponentProps<{ id: string }, {}>;
type AdsEditorState = { store?: AdsModel; fileList: any[] };

/**
 * 广告位编辑页面
 */
@observer
export class AdsEditor extends React.Component<AdsEditorProps, AdsEditorState> {

    private isEditMode: boolean;

    constructor(props) {
        super(props);
        this.initState();
    }

    private initState() {
        let store: AdsModel;

        this.isEditMode = this.props.route.path !== 'ads/create';

        if (!this.isEditMode) { // 创建
            store = new AdsModel();
        }
        else { // 编辑
            store = new AdsModel(this.props.params.id);
            store.fetchData().catch(res => {
                message.error(`数据请求失败`, 2.5);
            });
        }

        this.state = {
            store,
            fileList: []
        };
    }

    private onSubmit = () => {
        this.state.store.save().then(
            res => message.success(res.message, CREATE_SUCCESS_REDIRECT_DELAY, () => {
                if (!this.isEditMode) {
                    location.href = '#/content/assets/ads/manager'
                }
            }),
            res => message.error(res.message, 2.5)
        );
    }

    private renderAdsOptions() {
        var {store, fileList} = this.state;

        return store.data.items.map((ad, index) => {
            if (!fileList[index] && ad.imageUrl) {
                fileList[index] = [{ uid: -1, url: ad.imageUrl }];
            }

            let onUpdate = e => {
                ad.imageUrl = e.length ? e[0].url : "";
            };
            let onChange = e => {
                fileList[index] = e;
                this.setState({ fileList: [...fileList] });
            };

            return <FormItem
                {...formItemLayout}
                key={index}
                label={`广告位${index + 1}`}
                extra="图片建议尺寸：360像素*150像素，长方形"
                required
                validateStatus={isUrl(ad.url) ? 'success' : 'error'}>
                <Input placeholder={linkPlaceholder} value={ad.url} onChange={e => ad.url = e.target['value']} />
                <ImageUploader
                    limit={1}
                    fileList={fileList[index]}
                    onUpdate={onUpdate}
                    onChange={onChange} />
            </FormItem>;
        });
    }

    render() {
        var {store} = this.state;
        return <Form horizontal>
            <FormItem
                {...formItemLayout}
                label="广告位名称"
                required
                validateStatus={store.nameValid ? "success" : "error"}
            >
                <Input placeholder="请输入广告位名称" value={store.data.name} onChange={e => store.data.name = e.target['value']} />
            </FormItem>
            {this.renderAdsOptions()}
            <FormItem {...tailFormItemLayout}>
                <Button type="primary" size="large" onClick={this.onSubmit} loading={store.isSubmiting} style={{ marginRight: 10 }}>保存</Button>
                <Button size="large" onClick={() => location.href = '#/content/assets/ads/manager'}>返回列表</Button>
            </FormItem>
        </Form>;
    }
}